<?php
namespace app\admin\controller;

use think\Loader;
use think\Db;

class Download extends Common
{

    private $obj;

    public function _initialize()
    {
        parent::_initialize();
    }

    public function index(){
        $data = db('download')->where(['delete'=>0])->order('create_time desc')->paginate(10);

        $count = count($data);

        $this->assign('data',$data);
        $this->assign('count',$count);
        return view();
    }

    public function upload(){
        return view();
    }

    public function save(){
        $title = $_POST['title'];
        $file = $_FILES;

        $file_name = date('YmdHis').$file['file']['name'];
        $path = '/alidata/www/jyxh.mgtvshop.com/public/download';
        if(!is_dir($path)){
            mkdir($path,0777,true);
        }

        if($file['file']['error'] == 1){
            echo "<script>
                    alert('上传文件过大！');
                    window.history.go(-1);
                  </script>";
        }elseif($file['file']['type'] == 'image/jpeg'){
            echo "<script>
                    alert('请勿上传图片！');
                    window.history.go(-1);
                  </script>";
        }else{
            if($title){
                $res = move_uploaded_file($file['file']['tmp_name'], $path.'/'.$file_name);
                if($res == 1){
                    $download_path = str_replace('/alidata/www/','http://',$path);
                    $download_path = str_replace('/public','',$download_path);
                    $download_url = $download_path.'/'.$file_name;

                    $data = [
                        'title' => $title,
                        'download_url' => ''.$download_url,
                        'create_time' => time()
                    ];
                    $res = db('download')->insert($data);
                    if($res){
                        echo "上传成功！";
                        echo "<script>
                            alert('上传成功！');
                          </script>";
                    }
                }else{
                    echo "<script>
                    alert('上传发生错误！');
                    window.history.go(-1);
                  </script>";
                }
            }else{
                echo "<script>
                        alert('标题不能为空');
                        window.history.go(-1);
                      </script>";
            }
        }

    }
}
